package com.handong.handserialprogram.module.singletask;

import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.model.entities.LatLngEntity;
import com.handong.handserialprogram.model.entities.MapPersonEntity;
import com.handong.handserialprogram.module.base.BaseFragment;
import com.handong.handserialprogram.module.base.BasePresenter;
import com.handong.handserialprogram.service.LocateService;
import com.handong.handserialprogram.threadpool.WorkExecutePool;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SystemUtil;
import com.handong.handserialprogram.voice.VoiceImpl;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

/**
 */
public class BaiduMapFragment extends BaseFragment implements AMap.OnMyLocationChangeListener {

    private static final String TAG = BaiduMapFragment.class.getSimpleName();

    public static final String MAP_DISTANCE = "map_distance";

    private MapView mAMapView;
    private AMap mAMap;
    private UiSettings uiSettings;

    private boolean isFirstLoc = true;
    private boolean mIsLocateToCenter = false;
    private boolean mIsTimer = false;
    private FrameLayout mLocationLayout;
    private LinearLayout mTipLayout;
    private TextView mReceiveTime;

    private int mDirect = 0;

    private double mLatitude = 4.9E-324, mLongitude = 4.9E-324;
    private LatLng mStartLatLng, mEndLatLng;

    private boolean mIsAddStaEnd = false;
    private boolean mIsMapLoadFinish = false;

    private int mTimerCount;
    private VoiceImpl mVoiceImpl;
    private HashMap<String, Marker> mCriminalMarkers;

    public BaiduMapFragment() {
    }

    public static BaiduMapFragment newInstance() {
        BaiduMapFragment fragment = new BaiduMapFragment();
        return fragment;
    }

    @Override
    protected int getContentViewID() {
        return R.layout.fragment_map;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //AMapOptions.CREATOR()

        mAMapView.onCreate(savedInstanceState);
        mAMap = mAMapView.getMap();
        //mAMap
        uiSettings=mAMap.getUiSettings();
        uiSettings.setScaleControlsEnabled(true);
        uiSettings.setZoomControlsEnabled(false);
        //mAMapView.showZoomControls(false);//放大
        mAMap.setMyLocationEnabled(true);
        //mAMapView.showScaleControl(true);//比例尺


        mAMap.setOnMapLoadedListener(mMapLoadedCallback);
        mCriminalMarkers = new HashMap<>();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EventBusUtil.register(this);
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initViewByID(View view) {
        mAMapView = (MapView) view.findViewById(R.id.baiduFragmentMap);
        //mAMapView = new MapView(getActivity());
        RelativeLayout layout = (RelativeLayout) view;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        params.leftMargin = 7;
        //layout.addView(mAMapView, 0, params);
        mLocationLayout = (FrameLayout) view.findViewById(R.id.mapBtnLocate);
        mTipLayout = (LinearLayout) findViewById(R.id.mapTipLayout);
        mReceiveTime = (TextView) findViewById(R.id.receiveLocateTip);

        mLocationLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LocateService.LOCATE_ERROR == mLatitude || LocateService.LOCATE_ERROR == mLongitude) {
                    AppUtil.showShortToast(getContext(), "当前位置无法定位");
                    return;
                }
                locateToCenter(mLatitude, mLongitude);
            }
        });
    }

    @Override
    protected void initViewData() {
    }

    /**
     * 设置起点终点。
     *
     * @param entity 经纬度实体类。
     */
    public void onSetLatLng(LatLngEntity entity) {
        //定义Maker坐标点 104.0396410000,30.6799390000
        mStartLatLng = new LatLng(entity.getStartLat(), entity.getStartLng());
        mEndLatLng = new LatLng(entity.getEndLat(), entity.getEndLng());

        //构建Marker图标
        BitmapDescriptor startBitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.map_route_start);

        BitmapDescriptor endBitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.map_route_end);
        //构建MarkerOption，用于在地图上添加Marker
        MarkerOptions startOption = new MarkerOptions()
                .position(mStartLatLng)
                .icon(startBitmap);

        MarkerOptions endOption = new MarkerOptions()
                .position(mEndLatLng)
                .icon(endBitmap);
        //在地图上添加Marker，并显示
        if (mAMap != null) {
            mAMap.addMarker(startOption);
            mAMap.addMarker(endOption);
        }
        mIsAddStaEnd = true;
        if (mIsMapLoadFinish) {
            controlMapPointVisible();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        JLog.d(TAG, "setUserVisibleHint " + isVisibleToUser );
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 10)
    public void receiveAMapLocation(AMapLocation location) {
        //JLog.d(TAG, "isResumed: " + isResumed() + "   |||   " + getUserVisibleHint());
        if (!isResumed()) {
            return;
        }
//        LocateService.MyLocationListener locData=new AMap.OnMyLocationChangeListener();.MyLocationListener();
//        LocationSource locData = new LocationSource();.Builder()
//                .accuracy(location.getBearing())
//                // 此处设置开发者获取到的方向信息，顺时针0-360
//                .direction(mDirect).latitude(location.getLatitude())
//                .longitude(location.getLongitude()).build();
//        mAMap.setLocationSource(locData);
//        mAMap.setLocationSource(new LocationSource() {
//            @Override
//            public void activate(OnLocationChangedListener onLocationChangedListener) {
//
//            }
//
//            @Override
//            public void deactivate() {
//
//            }
//        });

        mLongitude = location.getLongitude();
        mLatitude = location.getLatitude();
        if (AMapLocation.LOCATION_TYPE_WIFI == location.getLocationType()) {
            if (View.GONE == mTipLayout.getVisibility()) {
                mTipLayout.setVisibility(View.VISIBLE);
            }
            mReceiveTime.setText("GPS信号弱，定位可能存在误差");
        } else if (AMapLocation.LOCATION_TYPE_GPS == location.getLocationType()) {
            if (View.VISIBLE == mTipLayout.getVisibility()) {
                mTipLayout.setVisibility(View.GONE);
            }
        }
        if (isFirstLoc) {
            isFirstLoc = false;
            mIsLocateToCenter = true;
            mLocationLayout.setVisibility(View.VISIBLE);
        }
        if (mIsLocateToCenter) {
            locateToCenter(mLatitude, mLongitude);
        }
    }

    /**
     * 定位到中心点
     *
     * @param latitude  纬度。
     * @param longitude 经度。
     */
    private void locateToCenter(double latitude, double longitude) {
        LatLng latLng = new LatLng(latitude, longitude);
        mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,17.0f));
    }

    //@Subscribe(threadMode = ThreadMode.MAIN, priority = 60)
    //public void receiveCriminalLocate(MapPersonEntity entity) {
    //addMakerOnMap(entity, R.drawable.map_criminal_escape);
    //}

    public void addMakerOnMap(MapPersonEntity entity, int resId) {
        mIsLocateToCenter = false;
        Marker marker = mCriminalMarkers.get(entity.getId());
        LatLng latLng = new LatLng(entity.getLat(), entity.getLng());
        if (marker == null) {
            mTipLayout.setVisibility(View.VISIBLE);
            BitmapDescriptor descriptor = BitmapDescriptorFactory.fromResource(resId);
            MarkerOptions options = new MarkerOptions()
                    .position(latLng)
                    .icon(descriptor);
            marker = (Marker) mAMap.addMarker(options);
            mCriminalMarkers.put(entity.getId(), marker);

            if (mVoiceImpl == null) {
                mVoiceImpl = VoiceImpl.getInstance(getContext());
            }
            mVoiceImpl.addSound(R.raw.warning_receive_locate);
        }
        mReceiveTime.setText("接收犯人坐标时间:" + SystemUtil.getDateDetailsString());
        marker.setPosition(latLng);

        LatLngBounds bounds = new LatLngBounds.Builder()
                .include(latLng)
                .include(new LatLng(mLatitude, mLongitude))
                .build();
        if (mAMap != null) {
            mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds,0));
        }
    }

    public void removeMakerOnMap(String id) {
        if (mCriminalMarkers == null || mCriminalMarkers.isEmpty()) {
            return;
        }
        Marker marker = mCriminalMarkers.get(id);
        if (marker == null) {
            return;
        }
        marker.remove();
        mIsLocateToCenter = true;
        mCriminalMarkers.remove(id);
        if (mCriminalMarkers.isEmpty()) {
            mTipLayout.setVisibility(View.GONE);
        }
    }

    private void executeTimer() {
        if (mIsTimer) {
            mTimerCount = 0;
            return;
        }
        mIsTimer = true;
        WorkExecutePool.execute(new Runnable() {
            @Override
            public void run() {
                while (mTimerCount <= 5) {
                    mTimerCount++;
                    try {
                        JLog.d(TAG, "timer:" + mTimerCount);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                    if (mTimerCount > 5) {
                        break;
                    }
                }
                if (6 == mTimerCount) {
                    mHandler.sendMessage(Message.obtain());
                }
                JLog.d(TAG, "timer is destroy. " + mTimerCount);
            }
        });
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            mIsLocateToCenter = true;
            mIsTimer = false;
            mTimerCount = 0;
        }
    };

    /**
     * 地图加载完成回调方法。
     */
    private AMap.OnMapLoadedListener mMapLoadedCallback = new AMap.OnMapLoadedListener() {

        @Override
        public void onMapLoaded() {
            JLog.d(TAG, "onMapLoaded");
            mIsMapLoadFinish = true;
            if (mIsAddStaEnd) {
                controlMapPointVisible();
            }
            mAMap.setOnMapTouchListener(mMapTouchListener);
            BitmapDescriptor descriptor = BitmapDescriptorFactory.fromResource(R.drawable.map_car_normal);
            MyLocationStyle style=new MyLocationStyle();

            //mAMap.setMyLocationStyle(new MyLocationStyleCreator(descriptor.writeToParcel();new Parcel(MyLocationConfiguration.LocationMode.NORMAL
                    //, true, descriptor, 4521984, 4653056)));
            mAMap.setMyLocationStyle(style.myLocationIcon(descriptor).showMyLocation(true));

            mAMap.getUiSettings().setCompassEnabled(true);//指南针
            //LatLng latLng = new LatLng(30.633621, 103.978699);
            //addPoliceOnMap(latLng, R.drawable.map_police_normal);
        }
    };

    private AMap.OnMapTouchListener mMapTouchListener = new AMap.OnMapTouchListener() {
        @Override
        public void onTouch(MotionEvent motionEvent) {
            if (motionEvent.getAction() == 1) {
                if (isFirstLoc) {
                    return;
                }
                mIsLocateToCenter = false;
                executeTimer();
            } else {
                if (mTimerCount != 0) {
                    mTimerCount = 0;
                }
            }
        }
    };

    private void controlMapPointVisible() {
        LatLngBounds bounds = new LatLngBounds.Builder()
                .include(mStartLatLng)
                .include(mEndLatLng)
                .build();
        // 改变地图状态
        if (mAMap != null) {
            mAMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,0));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mAMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mAMapView.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBusUtil.unRegister(this);
        if (mAMap != null) {
            mAMap.setMyLocationEnabled(false);
            mAMap = null;
        }
        if (mAMapView != null) {
            mAMapView.onDestroy();
            mAMapView = null;
        }
    }

    @Override
    public void onDestroy() {
        //关闭计时器。
        mTimerCount = 10;
        // 关闭定位图层
        if (mLocationLayout != null) {
            mLocationLayout = null;
        }
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onMyLocationChange(Location location) {

    }
}
